<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\facade\Cache;

class Install extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = '';
    public function index()
    {
        $this->view->assign('step',url('index1'));
        return $this->view->fetch();
    }
    public function index1()
    {
        //系统变量
        $system_variables = [];
        $phpv = PHP_VERSION;
        $os = PHP_OS;
        $server = $_SERVER[ 'SERVER_SOFTWARE' ];

        $host = ( empty($_SERVER[ 'REMOTE_ADDR' ]) ? $_SERVER[ 'REMOTE_HOST' ] : $_SERVER[ 'REMOTE_ADDR' ] );
        $name = $_SERVER[ 'SERVER_NAME' ];

        $verison = !( version_compare(PHP_VERSION, '8.0.0') == -1 );
        //pdo
        $pdo = extension_loaded('pdo') && extension_loaded('pdo_mysql');
        $system_variables[] = [ "name" => "pdo", "need" => "开启", "status" => $pdo ];
        //curl
        $curl = extension_loaded('curl') && function_exists('curl_init');
        $system_variables[] = [ "name" => "curl", "need" => "开启", "status" => $curl ];
        //openssl
        $openssl = extension_loaded('openssl');
        $system_variables[] = [ "name" => "openssl", "need" => "开启", "status" => $openssl ];
        //gd
        $gd = extension_loaded('gd');
        $system_variables[] = [ "name" => "GD库", "need" => "开启", "status" => $gd ];
        //fileinfo
        $fileinfo = extension_loaded('fileinfo');
        $system_variables[] = [ "name" => "fileinfo", "need" => "开启", "status" => $fileinfo ];
        //sodium
        $sodium = extension_loaded('sodium');
        $system_variables[] = [ "name" => "sodium", "need" => "开启", "status" => $sodium ];

        $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(__FILE__, 4));
        $root_path = str_replace("../", DIRECTORY_SEPARATOR, $root_path);
//        echo '<pre>';
//        print_r($root_path);
//        exit;
        $dirs_list = [
            [
                "path" => $root_path . DIRECTORY_SEPARATOR,
                "path_name" => "/",
                "name" => "网站目录",
                "create"=>true
            ],
//            [
//                "path" => $root_path . DIRECTORY_SEPARATOR . ".env",
//                "path_name" => ".env",
//                "name" => "env",
//                "create"=>false
//            ],
            [
                "path" => $root_path . DIRECTORY_SEPARATOR . ".env.example",
                "path_name" => ".env.example",
                "name" => "env",
                "create"=>true
            ],
            [
                "path" => $root_path . DIRECTORY_SEPARATOR . 'runtime' . DIRECTORY_SEPARATOR,
                "path_name" => "/runtime",
                "name" => "runtime",
                "create"=>true
            ],
            [
                "path" => $root_path . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR,
                "path_name" => "/public/uploads",
                "name" => "upload",
                "create"=>true
            ],
//            [ "path" => $root_path . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR, "path_name" => "/app/install", "name" => "安装目录" ]
        ];
        //目录 可读 可写检测
        $is_dir = true;
        foreach ($dirs_list as $k => $v) {
            if($v[ 'create']){
                if($v['path'][ strlen($v['path']) - 1]==DIRECTORY_SEPARATOR){
                    if(!is_dir($v[ "path" ])){
                        @mkdir($v[ "path" ], 0755, true);
                    }else{
                        @chmod($v[ "path" ], 0755);
                    }

                }else{
                    $path_array = explode(DIRECTORY_SEPARATOR, $v[ "path" ]);
                    $tem_file_name = array_pop($path_array);
                    $tem_path = implode(DIRECTORY_SEPARATOR, $path_array);
                    if(is_dir($tem_path)){
                        @chmod($tem_path, 0755);
                    }else{
                        @mkdir($tem_path, 0755, true);
                    }
                    if(!is_file($v[ "path" ])){
                        file_put_contents($v[ "path" ], "");
                        @chmod($v[ "path" ], 0755);
                    }else{
                        @chmod($v[ "path" ], 0755);
                    }

                }
            }

            $is_readable = is_readable($v[ "path" ]);
            $is_write = is_write($v[ "path" ]);
            $dirs_list[ $k ][ "is_readable" ] = $is_readable;
            $dirs_list[ $k ][ "is_write" ] = $is_write;
            if (!$is_readable || !$is_write) {
                $is_dir = false;
            }
        }
        $this->assign("root_path", $root_path);
        $this->assign("system_variables", $system_variables);
        $this->assign("phpv", $phpv);
        $this->assign("server", $server);
        $this->assign("host", $host);
        $this->assign("os", $os);
        $this->assign("name", $name);
        $this->assign("verison", $verison);
        $this->assign("dirs_list", $dirs_list);
        if ($verison && $pdo && $curl && $openssl && $gd && $fileinfo && $is_dir) {
            $continue = true;
        } else {
            $continue = false;
        }
        $this->assign("continue", $continue);
        $this->view->assign('step',url('index2'));
        $this->view->assign('stup',url('index'));
        return $this->view->fetch();
    }
    public function index2()
    {
        $this->view->assign('step',url('index3'));
        $this->view->assign('stup',url('index1'));
        $this->view->assign('testdb',url('testdb'));
        $this->view->assign('getInstallInfo',url('getInstallInfo'));
        $this->view->assign('install',url('install'));
        $this->view->assign('root_url',$this->request->domain());
        return $this->view->fetch();
    }
    public function index3()
    {

    }
    public function testdb()
    {
//        return $this->success("数据库连接成功");
        $res = $this->testdbHand();
        if($res['code']==0){
            return $this->error($res['msg']);
        }
        return $this->success($res['msg'],'',$res['data']);
    }
    protected function testdbHand()
    {
        $dbport = $this->request->param("dbport", "");
        $dbhost = $this->request->param("dbhost", "");
        $dbuser =$this->request->param("dbuser", "");
        $dbpwd = $this->request->param("dbpwd", "");
        $dbname = $this->request->param("dbname", "");
        if ($dbport != "" && $dbhost != "") {
            $dbhost = $dbport != '3306' ? $dbhost . ':' . $dbport : $dbhost;
        }

        if ($dbhost == '' || $dbuser == '') {
            return [
                'code' => 0,
                'msg' => '数据库账号或密码不能为空'
            ];
        }

        if (!function_exists("mysqli_connect")) {
            return [
                'code' => 0,
                'msg' => 'mysqli扩展类必须开启'
            ];
        }

        $conn = @mysqli_connect($dbhost, $dbuser, $dbpwd);
        if ($conn) {
            if (empty($dbname)) {
                return [
                    'code' => 1,
                    'msg' => '数据库连接成功',
                    'data' => [
                        'status' => 1
                    ]
                ];
            } else {
                $has = mysqli_select_db($conn, $dbname);
                if (!$has) {
                    return [
                        'code' => 1,
                        'msg' => '数据库不存在,自动创建',
                        'data' => [
                            'status' => 1
                        ]
                    ];
                }else{
                    return [
                        'code' => 1,
                        'msg' => '数据库存在，覆盖数据库',
                        'data' => [
                            'status' => 2
                        ]
                    ];
                }
            }
            @mysqli_close($conn);
        } else {
            return [
                'code' => 0,
                'msg' => '数据库连接失败！'
            ];
        }
        return [
            'code' => 1,
            'msg' => '数据库链接成功',
            'data' => [
                'status' => 1
            ]
        ];
    }
    public function getInstallInfo()
    {

    }
    public function install()
    {
        $data = $this->request->param();
        set_time_limit(0);
        Cache::delete('install_data');
        Cache::set('install_status', 0);//进行中
        $check = $this->testdbHand();
        if($check['code']==0){
            $this->setSuccessLog([ $check['msg'], 'error' ]);
            return $this->error($check['msg']);
        }
        $admin_name = $this->request->param('admin_name', "");
        $username = $this->request->param('username', "");
        $password = $this->request->param('password', "");
        $password2 = $this->request->param('password2', "");

//        $site_name = $this->request->param('site_name', "");
//        $site_username = $this->request->param('site_username', "");
//        $site_password = $this->request->param('site_password', "");
//        $site_password2 = $this->request->param('site_password2', "");

        if ($admin_name == '' || $username == '' || $password == '') {
            $this->setSuccessLog([ '平台信息不能为空', 'error' ]);
            return fail('平台信息不能为空!');
        }


        if ($password != $password2) {
            $this->setSuccessLog([ '平台两次密码输入不一样，请重新输入', 'error' ]);
            return fail('平台两次密码输入不一样，请重新输入');
        }
    }
    protected function setSuccessLog($data)
    {
        if ($data[ 1 ] == 'error') {
            Cache::set('install_status', -1);
        }
        $time = @(int) microtime(true);
        $data[] = date('Y-m-d H:i:s', $time);
        $install_data = Cache::get('install_data') ?? [];
        $install_data[] = $data;
        Cache::set('install_data', $install_data);
    }
}